package model

import (
	"log"
	"webapp/utils"
)

// User 结构体
type User struct {
	Id       int
	Username string
	Password string
	Role     int
}

// AddUser 添加用户
func (user *User) AddUser() error {
	sqlStr := "insert into users(id,username,password,role) values (?,?,?,?)"
	inStmt, err := utils.DB.Prepare(sqlStr)
	if err != nil {
		return err
	}
	inStmt.Exec(user.Id, user.Username, user.Password, user.Role)
	log.Println("add user", user)
	return nil
}

func (user *User) DeleteUser() error {
	sqlStr := "delete from users where id = ?"
	inStmt, err := utils.DB.Prepare(sqlStr)
	if err != nil {
		return err
	}
	inStmt.Exec(user.Id)
	log.Println("remove user", user)
	return err
}

func GetUsersNewId() int {
	sqlStr := "select max(id) from users"
	rows, err := utils.DB.Query(sqlStr)
	var ret int
	if err != nil {
		return -1
	}
	rows.Next()
	rows.Scan(&ret)
	err = rows.Close()
	return ret + 1

}

func GetUserById(idFind int) (*User, error) {

	sqlStr := "select * from users where id = ?"
	rows, _ := utils.DB.Query(sqlStr, idFind)

	rows.Next()
	var id int
	var username string
	var password string
	var role int
	err := rows.Scan(&id, &username, &role, &password)
	if err != nil {
		return nil, err
	}
	u := &User{id, username, password, role}
	err = rows.Close()
	return u, nil
}

func GetUserByName(nameFind string) (*User, error) {

	sqlStr := "select id,username,role,password from users where username = ?"
	rows, _ := utils.DB.Query(sqlStr, nameFind)

	rows.Next()
	var id int
	var username string
	var password string
	var role int
	err := rows.Scan(&id, &username, &role, &password)
	if err != nil {
		return nil, err
	}
	u := &User{id, username, password, role}
	err = rows.Close()
	return u, err
}

func GetUserList() ([]*User, error) {
	sqlStr := "select * from users"
	rows, _ := utils.DB.Query(sqlStr)
	var id int
	var username string
	var password string
	var role int
	var userList []*User
	for rows.Next() {

		err := rows.Scan(&id, &username, &role, &password)
		if err != nil {
			return nil, err
		}
		u := &User{id, username, password, role}
		userList = append(userList, u)
	}
	err := rows.Close()
	return userList, err
}

func ToggleManager(userId int) error {
	user, err := GetUserById(userId)
	if user == nil {
		return err
	}
	var newRole int

	if user.Role == 1 {
		newRole = 0
	} else {
		newRole = 1
	}
	sqlStr := "update users set role = ? where id = ? "
	inStmt, err := utils.DB.Prepare(sqlStr)
	if err != nil {
		return err
	}
	_, err = inStmt.Exec(newRole, userId)
	if err != nil {
		return err
	}
	log.Println(user.Username, "has new Role value", newRole)
	return err
}
